package com.itheima.tlias.controller;

import com.itheima.tlias.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Session会话跟踪
 * @author
 * @version 1.0.1
 * @date 2023-04-10 15:52:06
 */
@RestController
@Slf4j
public class CookieSessionController {

    @GetMapping("/s1")
    public Result s1(HttpServletRequest request){
        //创建或者获取Session，如果Session已经存在了，则直接获取
        HttpSession session = request.getSession();
        System.out.println("s1" + session.getId());
        //session往会话对象中存值
        session.setAttribute("sessionKey", "sessionValue");
        return Result.success();
    }

    @GetMapping("/s2")
    public Result s2(HttpServletRequest request, HttpSession session){
        //创建或者获取Session，如果Session已经存在了，则直接获取
        HttpSession session1 = request.getSession();
        System.out.println("session1" + session1.getId());
        HttpSession session2 = request.getSession();
        System.out.println("session2" + session2.getId());
        System.out.println(session1 == session2);
        System.out.println(session.getId());
        //向session中取值
        Object value = session2.getAttribute("sessionKey");
        System.out.println("value = " + value);

        return Result.success();
    }

    // Tomcat会把请求数据封装到一个对象中 Request   --> HttpServletRequest
    // Tomcat会把响应数据封装到一个对象中 Response  --> HttpServletResponse

    @GetMapping("/c/send")
    public Result send(HttpServletResponse response){
        Cookie cookie = new Cookie("username", "zhangsan");
        //通过响应头的形式发送
        response.addCookie(cookie);
        return Result.success();
    }

    @GetMapping("/c/get")
    public Result get(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            }
        }
        return Result.success();
    }

    @GetMapping("/c/get2")
    public Result get(@CookieValue(name = "username") String username){
        System.out.println(username);
        return Result.success();
    }

}
